package com.yc.cloud.openai.portal.dao.impl;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.yc.cloud.common.basic.exception.Asserts;
import com.yc.cloud.openai.portal.common.PortalErrorTips;
import com.yc.cloud.openai.portal.dao.GPTChatClient;
import com.yc.cloud.openai.portal.dto.gpt.GPTCreateDatasetCollectionDataDto;
import com.yc.cloud.openai.portal.dto.gpt.GptDatasetCollectionCreateDto;
import com.yc.cloud.openai.portal.dto.gpt.GptDatasetCreateDto;
import com.yc.cloud.openai.portal.dto.gpt.GptDatasetUpdateDto;
import com.yc.cloud.openai.portal.dto.request.ChatCompletionsRequest;
import com.yc.cloud.openai.portal.dto.response.GPTChatResponseResult;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

@Component("FASTGPT")
@Slf4j
public class FastGPTClientImpl implements GPTChatClient {

    @Value("${custom.ai.fastgpt.url}")
    private String url;

    @Value("${custom.ai.fastgpt.api-key}")
    private String apiKey;

    @Override
    public Flux<String> completionsByStream(ChatCompletionsRequest request) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'completionsByStream'");
    }

    @Override
    public String completions(ChatCompletionsRequest request) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'completions'");
    }

    @Override
    public GPTChatResponseResult<GPTCreateDatasetCollectionDataDto> createDatasetCollection(
            GptDatasetCollectionCreateDto request) {
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("datasetId", request.getDatasetId());
        dataMap.put("parentId", null);
        dataMap.put("trainingType", request.getTrainingType());
        dataMap.put("chunkSize", request.getChunkSize());
        dataMap.put("chunkSplitter", request.getChunkSplitter());
        dataMap.put("qaPrompt", request.getQaPrompt());
        dataMap.put("metadata", new HashMap<>());

        String result = HttpUtil.createPost(url + "/core/dataset/collection/create/localFile")
                .header("Authorization", "Bearer " + apiKey)
                .form("file", request.getFile())
                .form("data", JSONUtil.toJsonStr(dataMap))
                .execute()
                .body();
        log.info("FASTGPT createDatasetCollection result:{}", result);

        if (StrUtil.isEmpty(result)) {
            Asserts.fail(PortalErrorTips.CREATE_DATASET_COLLECTION_FAILED);
        }
        if (!JSONUtil.isTypeJSON(result)) {
            Asserts.fail(PortalErrorTips.CREATE_DATASET_COLLECTION_FAILED);
        }
        val typeRef = new TypeReference<GPTChatResponseResult<GPTCreateDatasetCollectionDataDto>>() {
        };
        val response = JSONUtil.toBean(result, typeRef, false);
        return response;
    }

    @Override
    public GPTChatResponseResult<String> createDataset(GptDatasetCreateDto param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("parentId", null);
        paramMap.put("type", "dataset");
        paramMap.put("name", param.getName());
        paramMap.put("intro", param.getDescription());
        paramMap.put("avatar", "");
        paramMap.put("vectorModel", param.getVectorModel());
        paramMap.put("agentModel", param.getAgentModel());

        String result = HttpUtil.createPost(url + "/core/dataset/create")
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(paramMap))
                .execute()
                .body();

        if (StrUtil.isEmpty(result)) {
            Asserts.fail("创建知识库失败");
        }
        if (!JSONUtil.isTypeJSON(result)) {
            Asserts.fail("创建知识库失败,错误信息:" + result);
        }
        val response = JSONUtil.toBean(result, GPTChatResponseResult.class);
        val gptResponse = new GPTChatResponseResult();
        // 200 表示成功
        if (response.getCode() == GPTChatResponseResult.SUCCESS_CODE) {
            gptResponse.setData((String) response.getData());
            gptResponse.setMessage(GPTChatResponseResult.SUCCESS_MESSAGE);
        } else {
            gptResponse.setMessage(response.getMessage());
        }
        gptResponse.setCode(response.getCode());
        return gptResponse;
    }

    @Override
    public GPTChatResponseResult deleteDataset(String datasetId) {
        String result = HttpUtil.createGet(url + "/core/dataset/delete")
                .header("Authorization", "Bearer " + apiKey)
                .form("id", datasetId)
                .execute()
                .body();

        if (StrUtil.isEmpty(result)) {
            log.error("删除知识库失败,错误信息:{}", result);
            Asserts.fail(PortalErrorTips.DELETE_DATASET_FAILED);
        }
        if (!JSONUtil.isTypeJSON(result)) {
            log.error("删除知识库失败,错误信息:{}", result);
            Asserts.fail(PortalErrorTips.DELETE_DATASET_FAILED);
        }
        return JSONUtil.toBean(result, GPTChatResponseResult.class);
    }

    @Override
    public GPTChatResponseResult updateDataset(GptDatasetUpdateDto gptDatasetUpdateDto) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'updateDataset'");
    }

    @Override
    public GPTChatResponseResult deleteDatasetCollection(String collectionId) {
        String result = HttpUtil.createGet(url + "/core/dataset/collection/delete")
                .header("Authorization", "Bearer " + apiKey)
                .form("id", collectionId)
                .execute()
                .body();
        if (StrUtil.isEmpty(result)) {
            log.error("删除知识库集合失败,错误信息:{}", result);
            Asserts.fail(PortalErrorTips.DELETE_DATASET_COLLECTION_FAILED);
        }
        if (!JSONUtil.isTypeJSON(result)) {
            log.error("删除知识库集合失败,错误信息:{}", result);
            Asserts.fail(PortalErrorTips.DELETE_DATASET_COLLECTION_FAILED);
        }
        return JSONUtil.toBean(result, GPTChatResponseResult.class);
    }
}
